/*********************************************************************************
  *Copyright (c)    2021   xldeng
  *FileName:        LFU.cpp.c
  *Author:          xldeng
  *Version:         1.0
  *Date:            2021/2/17 21:00
  *Description:     
  *Others:          
  *Function List:   
     1.…………
  *History:  
     1.Date:
       Author:
       Modification:
**********************************************************************************/
//请你为 最不经常使用（LFU）缓存算法设计并实现数据结构。
#include "../header.h"

struct Node {
    int key, val, freq;

    Node(int _key, int _val, int _freq) : key(_key), val(_val), freq(_freq) {}
};

class LFUCache {
public:
    explicit LFUCache(int _capacity) {
        minfreq = 0;
        capacity = _capacity;
        key_table.clear();
        freq_table.clear();
    }

    int get(int key) {
        if (capacity == 0)
            return -1;
        auto it = key_table.find(key);
        if (it == key_table.end())
            return -1;
        auto node = it->second;
        int freq = node->freq;
        int value = node->val;
        freq_table[freq].erase(node);
        if (freq_table[freq].empty()) {
            freq_table.erase(freq);
            if (minfreq == freq)
                minfreq++;
        }
        freq_table[freq + 1].push_front(Node(key,value,freq + 1));
        key_table[key] = freq_table[freq + 1].begin();
        return value;
    }

    void put(int key, int value) {
        if (capacity == 0)
            return;
        auto it = key_table.find(key);
        if (it == key_table.end()) {
            if (key_table.size() == capacity) {
                auto it2 = freq_table[minfreq].back();
                key_table.erase(it2.key);
                freq_table[minfreq].pop_back();
                if (freq_table[minfreq].empty())
                    freq_table.erase(minfreq);
            }
            freq_table[1].push_front(Node(key, value, 1));
            key_table[key] = freq_table[1].begin();
            minfreq = 1;
        } else {
            auto node = it->second;
            int freq = node->freq;
            freq_table[freq].erase(node);
            if (freq_table[freq].empty()) {
                freq_table.erase(freq);
                if (minfreq == freq)
                    minfreq++;
            }
            freq_table[freq + 1].push_front(Node(key, value, freq + 1));
            key_table[key] = freq_table[freq + 1].begin();
        }

    }

private:
    int minfreq, capacity;
    unordered_map<int, list<Node>::iterator> key_table;
    unordered_map<int, list<Node>> freq_table;
};